
/**
 * 页面失活(无操作)
 * @param {() => void} callback 页面一定时长无操作时触发
 * @param {number} [timeout=30] 时长，默认30m，单位：分钟
 * @param {boolean} [immediate=false] 是否立即开始，默认 false
 * @param {any} that 回调函数中的 this
 * @returns
 */


class behavior {
    private pageTimer: any = undefined;
    private beginTime: number = 0;
    callback: Function;
    timeout: { noActionLogoutMinutes: number };
    constructor(callback: Function, addSubjectForm = { noActionLogoutMinutes: 30 }, immediate: boolean = false) {
        this.callback = callback;
        this.timeout = addSubjectForm;
        if (immediate) {
            this.onStartDeactivated();
        }
    }
    // 初始化清除定时器
    private onClearTimer = () => {
        this.pageTimer && clearTimeout(this.pageTimer);
        this.pageTimer = undefined;
    }
    // 开始计时
    private onStartTimer = () => {
        const currentTime = Date.now();
        if (this.pageTimer && currentTime - this.beginTime < 1000) {
            return;
        }
        this.onClearTimer();
        this.beginTime = currentTime;
        if (this.timeout?.noActionLogoutMinutes === 0 || this.timeout?.noActionLogoutMinutes === '0' || !this.timeout?.noActionLogoutMinutes) return;
        this.pageTimer = setTimeout(() => {
            this.callback();
        }, this.timeout.noActionLogoutMinutes * 1000 * 60);
    };

    /**
     * 开始监听用户是否有操作页面（无操作）
     * */

    onStartDeactivated = () => {
        this.onStartTimer();
        [
            'mousemove',    //鼠标移动
            'mousedown',    //鼠标按下
            'touchstart',   //触摸屏幕（移动端）
            'wheel',        //鼠标滚轮
            'resize',       //页面尺寸变化
            'keydown',      //键盘输入
        ].map(event => {
            window.addEventListener(event, this.onStartTimer)
        })
    };
    /**
     * 页面失活（无操作）
     * */
    onStopDeactivated = () => {
        this.onClearTimer();
        [
            'mousemove',    //鼠标移动
            'mousedown',    //鼠标按下
            'touchstart',   //触摸屏幕（移动端）
            'wheel',        //鼠标滚轮
            'resize',       //页面尺寸变化
            'keydown',      //键盘输入
        ].map(event => {
            window.removeEventListener(event, this.onStartTimer)
        })
    };
}

export default behavior;